package com.jadows.tdog.message.handler.pipline.impl;

import cn.hutool.core.util.BooleanUtil;
import com.jadows.tdog.domain.ChatMessage;
import com.jadows.tdog.domain.Contact;
import com.jadows.tdog.enums.ServiceExceptionEnum;
import com.jadows.tdog.exception.ServiceException;
import com.jadows.tdog.message.handler.pipline.IMessageProcess;
import com.jadows.tdog.service.ContactService;
import com.jadows.tdog.util.UnionUtil;
import io.netty.channel.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 黑名单消息处理器
 *
 * @author taojiacheng
 */
@Service("messageBlockProcess")
@Slf4j
@RequiredArgsConstructor
public class MessageBlockProcess implements IMessageProcess {

    final ContactService contactService;

    @Override
    public ChatMessage handlerMessage(ChatMessage message, Channel channel) {
        String fromUid = message.getFromUid();
        String toUid = message.getToUid();
        String unionId = UnionUtil.getUnionId(fromUid, toUid);
        // 获取联系人
        Contact contact = contactService.findContactByUnionId(unionId);
        if (contact == null) {
            return message;
        }
        Contact.ContactInfo fromUser = contact.getFromUser();
        if (BooleanUtil.isTrue(fromUser.getBlocked())) {
            log.warn("联系人:{} , {} 已屏蔽当前对话", fromUser.getNickname(), fromUser.getUid());
            throw new ServiceException(ServiceExceptionEnum.CONTACT_IN_BLOCK_LIST);
        }
        Contact.ContactInfo toUser = contact.getToUser();
        if (BooleanUtil.isTrue(toUser.getBlocked())) {
            log.warn("联系人:{} , {} 已屏蔽当前对话", toUser.getNickname(), toUser.getUid());
            throw new ServiceException(ServiceExceptionEnum.CONTACT_IN_BLOCK_LIST);
        }
        return message;
    }
}
